﻿using Common.Cache;
using Common.Model;
using EMail.Interface;
using MimeKit.Text;
using MongoDB;
using MongoDB.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;

namespace Quartz.Service
{
    public class TaskTipService :ITaskTipService
    {
        private readonly ICache _cache;
        private readonly ISendMailKit _sendMailKit;
        private readonly IMongoDB _mongoDB;
        public TaskTipService(ICache cache, ISendMailKit sendMailKit, IMongoDB mongoDB)
        {
            _cache = cache;
            _sendMailKit = sendMailKit;
            _mongoDB = mongoDB;
        }

        /// <summary>
        /// 发送错误提醒邮件
        /// </summary>
        /// <param name="TaskInfo"></param>
        public async Task SendErrorTipEmail(Mongo_TaskManageModel TaskInfo, Exception ex)
        {
            var TipCache = _cache.Get<TipModel>($"ErrorCache_{TaskInfo.guid}");
            if (TipCache == null)
            {
                TipCache = new TipModel();
            }
            TaskInfo.MaxTipNum = TaskInfo.MaxTipNum.HasValue ? TaskInfo.MaxTipNum.Value : 1;
            TaskInfo.ErrorNumTip = TaskInfo.ErrorNumTip.HasValue ? TaskInfo.ErrorNumTip.Value : 1;
            TipCache.ErrorCount++;
            if (TipCache.TipCount < TaskInfo.MaxTipNum&&TipCache.ErrorCount >= TaskInfo.ErrorNumTip)
            {
                var EmailConfig = await _mongoDB.GetCollection<Mongo_EmailConfig>("Email_Config").FindInfoAsync(m => true);
                var isSend = EmailConfig != null &&
                    !EmailConfig.EmailAccount.IsNullOrWhiteSpace() &&
                    !EmailConfig.EmailPassword.IsNullOrWhiteSpace() &&
                    !EmailConfig.SmtpHost.IsNullOrWhiteSpace() &&
                    !EmailConfig.TipEmail.IsNullOrWhiteSpace();
                if (isSend)
                _sendMailKit.Connection(new EMail.Model.MailServerConfigModel 
                {
                    ServerHost=EmailConfig.SmtpHost,
                    ServerPort=EmailConfig.SmtpPort.HasValue ? EmailConfig.SmtpPort.Value:465,
                    IsSsl=EmailConfig.IsSsl==1,
                    EmailAccount=EmailConfig.EmailAccount,
                    EmailPassword=EmailConfig.EmailPassword
                });
                var Recipients = new List<EMail.Model.RecipientsModel>();
                Recipients.Add(new EMail.Model.RecipientsModel
                {
                    ReceiveMail = EmailConfig.TipEmail//收件邮箱
                });
                _sendMailKit.SendEmail(new EMail.Model.SendMailBodyModel
                {
                    Recipients = Recipients,//收件箱（支持群发，所以是List集合）
                    SenderAddress = EmailConfig.EmailAccount,//发送箱
                    Subject = "Quartz调度错误提醒",//主题
                    Body = $"Quartz定时调度任务发生报错。任务【{TaskInfo.TaskName}】,Url:【{TaskInfo.TaskUrl}】连续报错:{TipCache.ErrorCount}次,错误信息:【{ex.Message}】,请及时处理!",//邮件内容
                    MailBodyType= TextFormat.Text
                });
                TipCache.TipCount++;
            }
            _cache.Set($"ErrorCache_{TaskInfo.guid}", TipCache);
        }
    }
}
